import type { DictDto } from '@/api/common';
import type { DictKeyEnum } from '@/enums/dict.enums';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';
import { CommonApi } from '@/api/common';
import { DICT_DATA } from '@/enums';
import { dictVal2Text } from '@/utils/dict.utils';
import { isEmpty, isNumber, isString } from '@/utils/is.utils';
import { ls } from '@/utils/ls.utils';

export const useDictStore = defineStore('dictStore', () => {
  // 字典数据
  const dictList = ref<DictType>(ls.get(DICT_DATA, {}));

  const originalDict = ref<DictDto[]>([]);

  // 获取字典
  const handleGetDictInfo = async () => {
    const res = await CommonApi.getDictTree();
    originalDict.value = res;
    updateDict(res);
    return res;
  };

  /**
   * 更新字典
   * @param res
   * @returns
   */
  const updateDict = (res: DictDto[]) => {
    dictList.value = res.reduce((c: DictType, v) => {
      const { dictType } = v;

      if (!c[dictType]) {
        c[dictType] = [];
      }

      c[dictType].push({
        label: v.label,
        value: v.value
      });

      return c;
    }, {});

    ls.set(DICT_DATA, dictList.value);
    return res;
  };

  // 获取字典数据
  const getCodeDicts = (dictCode: string): DictItem[] => {
    console.warn(`getCodeDicts: 字典编码【${dictCode}】获取失败`);
    return dictList.value[dictCode] || [];
  };

  const getDictLabel = computed(() => {
    return (dictValue: unknown, dictType: DictKeyEnum) => {
      if (isEmpty(dictList.value)) {
        return '';
      }
      if (!isString(dictValue) && !isNumber(dictValue)) {
        return dictValue;
      }
      return dictVal2Text(String(dictValue), dictList.value[dictType]);
    };
  });

  const getDictCodeList = computed(() => {
    return (dictType: DictKeyEnum) => {
      return dictList.value[dictType];
    };
  });

  return {
    dictList,
    getDictLabel,
    getDictCodeList,
    getCodeDicts,
    handleGetDictInfo
  };
});
